<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>WebSocket Test</title>
</head>
<body>

<label for="text"></label><input id="text" type="text"/>
<button onclick="sendMessage()">发送消息</button>
<button onclick="closeWebSocket()">关闭连接</button>
<div id="message"></div>


<script type="text/javascript">
  let websocket = null;
  let devices = {};  // 存储设备信息

  //判断当前浏览器是否支持WebSocket
  if ('WebSocket' in window) {
    websocket = new WebSocket("ws://localhost:8089/renren-fast/websocket/font");
  } else {
    alert('Not support websocket');
  }

  //连接发生错误的回调方法
  websocket.onerror = function () {
    showMessage("打开连接失败");
  };

  //连接成功建立的回调方法
  websocket.onopen = function (event) {
    showMessage("打开连接成功");
  }

  //接收到消息的回调方法
  websocket.onmessage = function (event) {
    showMessage(event.data);
  }

  //更新设备信息表格
  function updateTable() {
    let tableBody = document.getElementById('device-table').getElementsByTagName('tbody')[0];
    tableBody.innerHTML = "";  // 清空当前的行
    for (let gwSN in devices) {
      let newRow = tableBody.insertRow();
      newRow.insertCell().innerHTML = gwSN;
      newRow.insertCell().innerHTML = devices[gwSN].U;
      newRow.insertCell().innerHTML = devices[gwSN].I;
      newRow.insertCell().innerHTML = devices[gwSN].P;
      newRow.insertCell().innerHTML = devices[gwSN].time;
      // 其他属性...
    }
  }

  //连接关闭的回调方法
  websocket.onclose = function () {
    showMessage("关闭连接成功");
  }

  //监听窗口关闭事件，当窗口关闭时，主动关闭WebSocket连接
  window.onbeforeunload = function () {
    websocket.close();
  }

  function showMessage(message) {
    document.getElementById('message').innerHTML += message + '<br/>';
  }

  function closeWebSocket() {
    websocket.close();
  }

  //发送消息
  function sendMessage() {
    const message = document.getElementById('text').value;
    websocket.send(message);
  }
</script>
</html>
